/**
 * ReportGear(2011)
 */
package com.reportgear.core.util;

import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 图像服务类
 * 
 * @version 1.0 2011-5-8
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 */
public class ImageUtils {
	private static final Logger logger = LoggerFactory.getLogger(ImageUtils.class.getName());

	private static Map<String, Image> imageMap = new HashMap<String, Image>();

	/**
	 * 读取文件
	 * 
	 * @param name
	 *            文件标识
	 * @return 图形对象
	 */
	public static Image readImage(String name) {
		Image image = imageMap.get(name);
		if (image != null) {
			return image;
		}

		InputStream input = readResource(name);
		if (input == null) {
			return null;
		}

		Image newImage = null;
		try {
			newImage = readImage(input);
			input.close();
		} catch (IOException ex) {
			logger.warn(ex.getMessage());
		}

		imageMap.put(name, newImage);

		return newImage;
	}

	/**
	 * 读取图标
	 * 
	 * @param name
	 *            名称
	 * @return 图标
	 */
	public static Icon readIcon(String name) {
		return new ImageIcon(readImage(name));
	}

	/**
	 * 读取图片
	 * 
	 * @param in
	 *            输入流
	 * @return 图片
	 * @throws IOException
	 */
	public static Image readImage(InputStream in) throws IOException {
		return ImageIO.read(in);
	}

	/**
	 * 读取资源
	 * 
	 * @param name
	 *            资源名
	 * @return 输入流
	 */
	public static InputStream readResource(String name) {
		InputStream is;
		if ((name == null) || (name.length() <= 0)) {
			return null;
		}

		is = ImageUtils.class.getResourceAsStream(name);
		if (is != null) {
			return is;
		}

		return readResourceByOtherWay(name);
	}

	private static InputStream readResourceByOtherWay(String name) {
		try {
			if (name.toLowerCase().startsWith("http:")) {
				return new URL(name).openStream();
			} else {
				File file = new File(name);
				if (file.exists()) {
					return new FileInputStream(name);
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
}
